import { createRouter, createWebHashHistory } from "vue-router";
import autoRegisterRoutes from "@/utils/autoRegisterRoutes";
import menuData from "@/data/menuData";
import Nprogress from "nprogress";
import "nprogress/nprogress.css";
import { useUserStore } from "@/stores";
import {config} from "@/global"

Nprogress.configure({ showSpinner: false,  speed: 500 });

const router = createRouter({
    history: createWebHashHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            redirect: '/login'
        },
        {
            path: '/layout',
            redirect:'/layout/dashboard',
            component: () => import("@/pages/layout/index.vue"),
            children:[
                {
                    name:'dashboard',
                    path: 'dashboard',
                    component: () => import("@/pages/dashboard/dashboard.vue"),
                }
            ]
        },
        {
            path: "/login",
            component: () => import("@/pages/login/index.vue")
        },
        {
            path: "/blank",
            component: () => import("@/pages/blank.vue")
        },
        {
            path: "/forbidden",
            component: () => import("@/pages/result/403.vue")
        },
        {
            path: "/:catchAll(.*)",
            component: () => import("@/pages/result/404.vue")
        },

    ]
});

router.beforeEach( async (to, from) => {
    Nprogress.start();
    if(to.meta.title){
        document.title = `${to.meta.title} - ${config.appName}`
    }
    const $store = useUserStore()
    // 每次刷新时，获取用户信息
    // 如果获取失败，则会跳转到 login
    if($store.token && !$store.isLogin){
        // 等待加载用户信息
        await $store.setUserInfo()
    }
    if(to.path != "/login" && !$store.isLogin){
        return "/login"
    }
    if(to.meta.isAdmin && !$store.isAdmin){
        return "/forbidden"
    }
    // const $store = main();
    // // 如果不等于登陆 并且还没有注册过路由
    // if (to.fullPath !== "/login" && !$store.isAutoRegistered) {
    //     autoRegisterRoutes(menuData);
    //     // 设置变量为true 代表已经注册过
    //     $store.isAutoRegistered = true;
    //     // 触发重定向
    //     return to.fullPath;
    // }
});
router.afterEach(() => {
    removeLoading();
    // 路由加载完成!
    Nprogress.done();
});

router.onError(() => {
    removeLoading();
    // 路由发生错误后销毁进度条
    Nprogress.remove();
});

const removeLoading = () => {
    document.querySelector("#loading-box")?.remove();
};
export default router;
